package com.vf.s.mvc.sys.controller;

import java.util.LinkedList;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.vf.core.controller.BaseController;
import com.vf.core.util.UuidUtil;
import com.vf.s.common.model.scene.Scene;
import com.vf.s.common.model.scene.BizSceneMenu;
import com.vf.s.common.model.sys.*;
import com.vf.s.mvc.sys.service.MenuService;
import com.vf.s.mvc.sys.service.RoleService;

public class RoleController extends BaseController{
	
	protected final Log LOG = Log.getLog(getClass());
	
	@Inject
	private RoleService srv;
	
	@Inject
	private MenuService srvMenu;

	public void index() {
		this.setAttr("scenes",Scene.dao.find("SELECT * FROM "+Scene.TABLE_NAME));
		render("list.html");
	}
	
	public void listData() {
		int pageNumber = getParaToInt("page", 1);
		int pageSize = getParaToInt("limit", 10);
		String keyword = getPara("keyword");

		String sqlExceptSelect = " FROM " + SysRole.TABLE_NAME + " o  WHERE 1=1 ";
		if (!StrKit.isBlank(keyword)) {
			sqlExceptSelect += " AND ( O.NAME LIKe '%" + keyword + "%' OR   O.CODE '%" + keyword + "%' ) ";
		}
		sqlExceptSelect += "  ORDER BY   O.SORT ASC ";
		Page<SysRole> page = SysRole.dao.paginate(pageNumber, pageSize, "select * ", sqlExceptSelect);
		renderLayuiPage(0, page.getList(), "", page.getTotalRow());
	}
	
	/***
	 * 保存
	 */
	public void save() {
		SysRole role = getModel(SysRole.class);
		if (StrKit.notBlank(role.getID())) {
			SysRole coderole=SysRole.dao.findFirst("SELECT * FROM "+SysRole.TABLE_NAME +" WHERE CODE=? AND ID!=?",role.getCODE(),role.getID());
			if(coderole!=null) {
				renderError("标识已存在！");
				return ;
			}
			SysRole namerole=SysRole.dao.findFirst("SELECT * FROM "+SysRole.TABLE_NAME +" WHERE NAME=? AND ID!=?",role.getNAME(),role.getID());
			if(namerole!=null) {
				renderError("名称已存在！");
				return ;
			}
			if (role.update()) {
				renderSuccess("更新成功！");
			} else {
				renderError("更新失败！");
			}
		} else {
			SysRole coderole=SysRole.dao.findFirst("SELECT * FROM "+SysRole.TABLE_NAME +" WHERE CODE=?",role.getCODE());
			if(coderole!=null) {
				renderError("标识已存在！");
				return ;
			}
			SysRole namerole=SysRole.dao.findFirst("SELECT * FROM "+SysRole.TABLE_NAME +" WHERE NAME=?",role.getNAME());
			if(namerole!=null) {
				renderError("名称已存在！");
				return ;
			}
			role.setID(UuidUtil.getUUID());
			if (role.save()) {
				renderSuccess("保存成功！");
			} else {
				renderError("保存失败！");
			}
		}

	}

	/***
	 * 删除
	 * 
	 * @throws Exception
	 */
	public void delete() throws Exception {
		String id = getPara("id");
		SysRole role = SysRole.dao.findById(id);
		if (role != null) {
			if (role.delete()) {
				renderSuccess("删除成功！");
			} else {
				renderError("删除失败！");
			}
		} else {
			renderError("数据不存在,请刷新后再试!");
		}
	}
	
	public void authTree() {
    	String roleId=this.getPara("roleId");
		List<SysMenu> list=SysMenu.dao.find("select t.id,t.parentId as pId, t.name, "
				+ " (CASE  WHEN (SELECT count(id) as count from sys_role_permissions where menuId=t.id and roleId=? )>0 THEN true ELSE  false END ) as checked   "
				+ " from sys_menu  t  ORDER BY t.sort asc",roleId);
		this.renderJson(list);
	}
	
	
	@Before(Tx.class)
	public void saveAuth() {
		String roleId = getPara("roleId");
		String targetId = this.getPara("targetId", "");
		String authIds = getPara("authIds");
		SysRole role = SysRole.dao.findById(roleId);
		if (role != null) {
			List<String>  arr = JSONObject.parseArray(authIds, String.class);  
			List<String> sqlList = new LinkedList<String>();
			if (arr != null && arr.size() > 0) {
				if(StrKit.isBlank(targetId)) {
					sqlList.add("DELETE  FROM SYS_ROLE_PERMISSIONS WHERE ROLEID='" + roleId + "' and TARGETID is null  ");
				}else {
					sqlList.add("DELETE  FROM SYS_ROLE_PERMISSIONS WHERE ROLEID='" + roleId + "' and TARGETID='"+targetId+"' ");
				}
				if (SysRole.excuteSql(sqlList)) {
					sqlList.clear();
					for (String menuId : arr) {
						sqlList.add("INSERT INTO SYS_ROLE_PERMISSIONS (ID,ROLEID,MENUID,TARGETID) VALUES('" + UuidUtil.getUUID() + "','"
								+roleId  + "','" +menuId  + "','" +targetId  + "')");
					}
					if (SysRole.excuteSql(sqlList)) {
						renderSuccess("授权成功！");
					} else {
						renderError("授权操作失败!");
					}
				} else {
					renderError("授权操作失败!");
				}
			} else {
				if(StrKit.isBlank(targetId)) {
					sqlList.add("DELETE  FROM SYS_ROLE_PERMISSIONS WHERE ROLEID='" + roleId + "' and TARGETID is null  ");
				}else {
					sqlList.add("DELETE  FROM SYS_ROLE_PERMISSIONS WHERE ROLEID='" + roleId + "' and TARGETID='"+targetId+"' ");
				}
				if (SysRole.excuteSql(sqlList)) {
					renderSuccess("取消授权成功！");
				}else {
					renderError("取消授权失败!");
				}
			}

		} else {
			renderError("角色信息不存在,请刷新后再试!");
		}
	}
	
	
	public void authSceneTree() {
    	String roleId=this.getPara("roleId");
    	String sceneId=this.getPara("sceneId");
		List<BizSceneMenu> list=BizSceneMenu.dao.find("select t.id,t.parentId as pId, t.name, "
				+ " (CASE  WHEN (SELECT count(id) as count from sys_role_permissions where menuId=t.id and roleId=? )>0 THEN true ELSE  false END ) as checked   "
				+ " from "+BizSceneMenu.TABLE_NAME+"  t  where t.SCENEID=? ORDER BY t.sort asc",roleId,sceneId);
		this.renderJson(list);
	}
	
	
	
}
